<?php
/**
 * Created by PhpStorm.
 * User: Lyq
 * Date: 2018/8/24
 * Time: 8:21
 */
namespace app\bussiness\controller;

use think\Exception;
use think\Db;

class Department extends Common
{
    public function index()
    {   header("Content-type:text/html;charset=utf-8");
        if(request()->isGet()){
            //设置标题
            $this->templateTitle("组织结构列表");

            $bussiness_id = $this->currentBussinessId();

            //获取一级部门
            $depart = Db::name("department")
                ->where("parent_id", '0')
                ->where('bussiness_id',$bussiness_id)
                ->group('bussiness_id')
                ->paginate(8);
            $this->assign("depart", $depart);

            return $this->fetch();
        }
        if(request()->isAjax()){
            $id = request()->param('id');
            $list = Db::name('department')
               ->where('parent_id',$id)
               ->order('display_order desc')
               ->select();
            if(!$list){
                return $this->ajaxError('此组织结构已无下设组织结构');
            }
            $html = '';
            foreach ($list as $k=>$v){
                $html .= '<div class="accordion" id="category_'.$v['id'].'" role="tablist" aria-multiselectable="true">
                    <div class="panel" style="background: none; border: none; -webkit-box-shadow: none; box-shadow: none;">
                        <div class="panel-heading" style="background: none; border: 1px solid #ebebeb;">
                            <i class="fa fa-plus" role="tab" id="category_header_'.$v['id'].'" data-toggle="collapse"
                               data-parent="#category_'.$v['id'].'" href="#category_collapse_'.$v['id'].'"
                               aria-expanded="true" aria-controls="category_collapse_'.$v['id'].'"
                               onclick="collapseCategory(\'category_header_'.$v['id'].'\',\''.$v['id'].'\')"></i>
                            <span class="panel-title">【ID：'.$v['id'].'】'.$v['title'].'</span>
                            <div style="float: right; margin-top: -4px;">
                                
                                <button type="button" class="btn btn-default btn-sm" onclick="modal(\''.url('add',['parent_id'=>$v['id']]).'\',\'添加下级组织结构\')">
                                    <i class="fa fa-plus"></i>
                                </button>
                                <button type="button" class="btn btn-default btn-sm" onclick="modal(\''.url('edit',['id'=>$v['id']]).'\',\'编辑组织结构\')">
                                    <i class="fa fa-edit"></i>
                                </button>
                                <button type="button" class="btn btn-default btn-sm department_delbtn" data-id="'.$v['id'].'"
                                       data-title="'.$v['title'].'">
                                    <i class="fa fa-times"></i>
                                </button>
                            </div>
                        </div>
                        <div id="category_collapse_'.$v['id'].'" class="panel-collapse collapse" role="tabpanel"
                             aria-labelledby="category_header_'.$v['id'].'" aria-expanded="true" style="height:0px;">
                            <div  id="depart_ment_con_'.$v['id'].'" class="panel-body">
                                
                            </div>
                        </div>
                    </div>
                </div>';
            }
            $html .= '';
            return $this->ajaxSuccess('',$html);
        }
    }


    public function add()
    {   $parent_id = request()->param("parent_id");
        $bussiness_id = $this->currentBussinessId();
        $info = Db::name('department')
            ->where('id',$parent_id)
            ->where('bussiness_id',$bussiness_id)
            ->find();

        if(request()->isGet()){
            if(!empty($parent_id)&&!$info){
                $this->error('此上级组织数据不存在');exit;
            }
            $this->layoutModal();
            $this->assign('parent',$info);
            return $this->fetch();
        }
        if (request()->isAjax())
        {
            $data = [
                'create_time'=>now_datetime(),
                'update_time'=>now_datetime()
            ];
            if(!empty($parent_id)){
                //有上级添加下级
                if(!$info){
                    return $this->ajaxError('此上级组织数据不存在');
                }
                $data['parent_id'] = $info['id'];
                $data['level'] = $info['level']+1;
                if($data['level']>config('max_department_level')){
                    return $this->ajaxError('组织结构限制'.config('max_department_level').'层以内');
                }
                $data['bussiness_id'] = $info['bussiness_id'];
            }else{

                $count = Db::name('department')
                    ->where('bussiness_id',$bussiness_id)
                    ->where('parent_id',0)
                    ->count();
                if($count){
                    $this->ajaxError('此商会已添加了顶级组织，请在顶级组织下添加');
                }
                $data['parent_id'] = 0;
                $data['level']=1;
                $data['bussiness_id'] = $bussiness_id;
            }

            $data['title'] = trim(input('title'));
            if(empty($data['title'])){
                return $this->ajaxError('请输入组织结构名称');
            }
            $data['display_order'] = intval(input('order'));
            try
            {
                //修改分类及其子类的可见性
                $addid = Db::name("department")
                    ->insertGetId($data);
                if($addid){
                    if(empty($parent_id)){
                        //无上级
                        $changeda = ['id_path'=>$addid];
                    }else{
                        $changeda = ['id_path'=>$info['id_path'].'-'.$addid];
                    }
                    Db::name("department")
                        ->where('id',$addid)
                        ->update($changeda);
                    return $this->ajaxSuccess("添加组织结构成功！");
                }else{
                    return $this->ajaxSuccess("添加组织结构失败！");
                }

            }
            catch (Exception $exception)
            {
                $this->ajaxError($exception->getMessage());
            }
        }
    }


    public function edit()
    {   $id = request()->param("id");
        $bussiness_id = $this->currentBussinessId();
        $depart = Db::name('department')->where('bussiness_id',$bussiness_id);

        if(request()->isGet()){
            $this->layoutModal();
            $info = $depart->where('id',$id)->find();
            if(!$info){
                $this->error('数据不存在或已删除');exit;
            }
            $parent = $depart->where('id',$info['parent_id'])->find();
            $this->assign('parent',$parent);
            $this->assign('info',$info);
            return $this->fetch();
        }
        if (request()->isAjax())
        {   $data = [
                'update_time' => now_datetime()
            ];
            $data['title'] = request()->param('title');
            if(empty($data['title'])){
                return $this->ajaxError('请输入组织结构名称');
            }
            $data['display_order'] = intval(input('order'));

            try
            {
                //修改分类及其子类的可见性
                $depart->where("id", $id)->update($data);

                return $this->ajaxSuccess("编辑组织结构成功！");
            }
            catch (Exception $exception)
            {
                $this->ajaxError($exception->getMessage());
            }
        }
    }

    public function remove(){
        $id = request()->param('id');

        $map['id'] = $id;
        $map['bussiness_id'] = $this->currentBussinessId();

        $info = Db::name('department')
            ->where($map)
            ->find();

        $del = Db::name('department')
            ->where($map)
            ->delete();
        if($del){

            if($info['parent_id'] > 0){
                Db::name('department')
                    ->where('id_path','like',"%-".$id."-%")
                    ->delete();

            }else{
                Db::name('department')
                    ->where('id_path','like',$id."-%")
                    ->delete();
            }


            return $this->ajaxSuccess('组织结构已删除');
        }else{
            return $this->ajaxError('删除失败');
        }
    }
}